'use strict';

const BaseController = require('../../core/base_controller');
const {redis_set_article} = require("../../../utils/init");
class ArticleController extends BaseController {
  // 获取文章列表
  async index() {
    const { ctx } = this;
    const { type, status, page = 1, pageSize = 10 } = ctx.query;

    // 构建查询条件
    const where = {};
    if (type) where.type = type;
    if (status !== undefined) where.status = status;

    const { count, rows } = await ctx.model.Article.findAndCountAll({
      where,
      order: [['created_at', 'DESC']],
      offset: (page - 1) * pageSize,
      limit: parseInt(pageSize),
    });

    this.success({
      list: rows,
      pagination: {
        total: count,
        current: parseInt(page),
        pageSize: parseInt(pageSize),
      },
    });
  }

  // 创建文章
  async create() {
    const { ctx } = this;
    const rules = {
      type: { type: 'string', required: true },
      content: { type: 'string', required: true },
      status: { type: 'enum', values: [0, 1], required: false, default: 1 },
    };

    try {
      ctx.validate(rules);
    } catch (err) {
      ctx.throw(400, '参数错误');
    }

    // 检查该类型是否已存在文章
    const existingArticle = await ctx.model.Article.findOne({
      where: { type: ctx.request.body.type }
    });

    if (existingArticle) {
      ctx.throw(400, '该类型的文章已存在');
    }

    const article = await ctx.model.Article.create(ctx.request.body);
    redis_set_article(ctx.app)
    this.success(article);
  }

  // 更新文章
  async update() {
    const { ctx } = this;
    const article = await ctx.model.Article.findByPk(ctx.params.id);

    if (!article) {
      ctx.throw(404, '文章不存在');
    }

    // 如果要修改类型，检查新类型是否已存在
    if (ctx.request.body.type && ctx.request.body.type !== article.type) {
      const existingArticle = await ctx.model.Article.findOne({
        where: {
          type: ctx.request.body.type,
          id: { [ctx.model.Sequelize.Op.ne]: ctx.params.id } // 排除当前文章
        }
      });

      if (existingArticle) {
        ctx.throw(400, '该类型的文章已存在');
      }
    }

    await article.update(ctx.request.body);
    redis_set_article(ctx.app)
    this.success(article);
  }

  // 删除文章
  async destroy() {
    const { ctx } = this;
    const article = await ctx.model.Article.findByPk(ctx.params.id);

    if (!article) {
      ctx.throw(404, '文章不存在');
    }

    await article.destroy();
    redis_set_article(ctx.app)
    this.success(null, '删除成功');
  }

  // 修改文章状态
  async updateStatus() {
    const { ctx } = this;
    const { id } = ctx.params;
    const { status } = ctx.request.body;

    // 验证状态值
    if (![0, 1,true,false].includes(status)) {
      ctx.throw(400, '状态值无效');
    }

    const article = await ctx.model.Article.findByPk(id);
    if (!article) {
      ctx.throw(404, '文章不存在');
    }

    await article.update({ status });
    redis_set_article(ctx.app)
    this.success(null, '状态更新成功');
  }
}

module.exports = ArticleController;
